<template>
  <el-card class='container'>
    <div class='title'>
      {{ $t('msg.chart.bmapChartTitle') }}
    </div>
    <div ref='target' class='box'></div>
  </el-card>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import { getChartMap } from '@/api/chart'
// 导入 bmap 模块
import 'echarts/extension/bmap/bmap.js'
import * as echarts from 'echarts'
import { useI18n } from 'vue-i18n'

const i18n = useI18n()

/**
 * 获取数据
 */
const chartData = ref([])
const getChartData = async () => {
  const res = await getChartMap()
  chartData.value = res
  renderBMap()
}
getChartData()

/**
 * 数据转化方法
 */
const convertData = (data) => {
  const res = []
  data.forEach(item => {
    const geoCoord = chartData.value.geoCoordMap[item.name]
    if (geoCoord) {
      res.push({
        name: item.name,
        value: [...geoCoord, item.value]
      })
    }
  })
  return res
}

/**
 * 初始化 echarts
 */
const target = ref(null) // 获取dom
let mChart
onMounted(() => {
  mChart = echarts.init(target.value)
})

/**
 * 渲染视图
 */
const renderBMap = () => {
  const options = {
    tooltip: {
      trigger: 'item'
    },
    bmap: {
      // 中心点
      center: [109.114129, 36.550339],
      // 缩放级别
      zoom: 5,
      // 是否可拖动
      roam: true
    },
    series: [
      {
        name: `营收（${i18n.t('msg.chart.unit')}）`,
        type: 'scatter',
        coordinateSystem: 'bmap',
        data: convertData(chartData.value.data),
        // 散点大小
        symbolSize: function (val) {
          return val[2] / 10
        },
        // 数据使用哪个下标的值
        encode: { value: 2 },
        emphasia: {
          label: {
            // 鼠标移入时，显示高亮
            show: true
          }
        },
        color: '#15803d'
      },
      {
        name: `营收 TOP 5（${i18n.t('msg.chart.unit')}）`,
        type: 'effectScatter',
        coordinateSystem: 'bmap',
        data: convertData(chartData.value.data.sort((a, b) => {
          return b.value - a.value
        }).splice(0, 6)),
        symbolSize: function (val) {
          return val[2] / 10
        },
        encode: { value: 2 },
        // 特效
        rippleEffect: {
          brushType: 'stroke'
        },
        // 显示地名
        label: {
          formatter: '{b}',
          position: 'right',
          show: true
        },
        // 层级
        zlevel: 2,
        color: '#15803d'
      }
    ]
  }
  mChart.setOption(options)
}
</script>

<style lang="scss" scoped>
.container {
  position: relative;
  .title {
    position: absolute;
    top: 28px;
    margin-left: 50%;
    transform: translateX(-50%);
    color: #333;
    font-size: 22px;
    font-weight: bold;
    z-index: 6;
  }
  .box {
    height: 462px;
  }
}
</style>
